import config from './util/config'
import {
  checkWechatEnv,
  parseQueryString,
  joinQueryString,
} from './util/index'
import { tokenAvailableNew_post } from '@/api/app/wechat'

// url查询参数
const query = parseQueryString()

// 如果在小程序环境，存储来自小程序的token
const heyjie_token =
  query.miniprogram_t || localStorage.getItem('heyjie-token')
if (heyjie_token) {
  localStorage.setItem('heyjie-token', heyjie_token)
}

const wechatAuthorizeConfig = {
  appid: config.wechat.appId,
  redirect_uri:
    config.wechat.useAuthorize +
    joinQueryString({
      redirectUrl: location.href,
    }),
  response_type: 'code',
  scope: 'snsapi_userinfo',
  state: config.wechat.appId,
}

checkWechatEnv((res) => {
  // 微信内
  if (res === 'wechat') {
    // 非小程序环境, 授权
    wxAuthorize()
  }
  if (res === 'miniprogram') {
    wxAuthorize()
  }
  // 微信外
  if (res === 'outOfWechat') {
    // 非微信环境, 根据配置决定是否授权
    if (config.wechat.notAllowdOutOfWechat) {
      wxAuthorize()
    }
  }
})

// 验证微信token
function wxAuthorize() {
  return new Promise((resolve, reject) => {
    const queryObject = parseQueryString()
    const wechatTokenFromUrl = queryObject.token
    const wechatTokenFromLocal = localStorage.getItem('wechatToken')
    const token = wechatTokenFromUrl || wechatTokenFromLocal // 优先使用url的token
    if (token) {
      // 如果url或者localStorage里有token, 验证有效性。如果无效：跳转授权。如果有效：继续登录
      tokenAvailableNew_post({
        data: {
          token: token,
        },
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded',
        },
      })
        .then((res) => {
          localStorage.setItem('wechatToken', token)
          resolve({
            isOld: !!+res.data,
            isFlagState: !!+res.data,
          })
        })
        .catch((res) => {
          console.log(res)
          location.replace(
            'https://open.weixin.qq.com/connect/oauth2/authorize' +
              joinQueryString(wechatAuthorizeConfig)
          )
        })
    } else {
      // 如果都没有，跳转授权
      location.replace(
        'https://open.weixin.qq.com/connect/oauth2/authorize' +
          joinQueryString(wechatAuthorizeConfig)
      )
    }
  })
}
